﻿using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using CCL.Utility;

namespace Server.Service
{
    /// <summary>
    /// 프로젝트 리스트 요청에 대한 서비스를 제공합니다.
    /// </summary>
    public class GetProjectList : IService
    {
        /// <summary>
        /// 프로젝트 리스트 요청 메시지의 본문
        /// </summary>
        private CCL.SocketMessage.Request.GetProjectList m_getProjectList = null;

        /// <summary>
        /// 새로운 서비스를 생성합니다.
        /// </summary>
        /// <param name="getProjectList">프로젝트 리스트 요청 메시지 본문</param>
        public GetProjectList(CCL.SocketMessage.Request.GetProjectList getProjectList)
        {
            m_getProjectList = getProjectList;
        }

        /// <summary>
        /// 서비스를 시작합니다.
        /// </summary>
        /// <returns>전송할 byte배열</returns>
        public byte[] Execute()
        {
            byte[] returnBytes = null;
            using (SqlConnection conn = new SqlConnection(Properties.Resources.ConnectionString))
            {
                try
                {
                    conn.Open();

                    SqlCommand sqlCmd = new SqlCommand(@"
                        SELECT 
                            [Project].projectId AS pid, 
                            [Project].projectName AS pname, 
                            [Project].headRevision AS head, 
                            [Project].projectOwnerId AS poid, 
                            [User].userId AS uid, 
                            [User].email AS email, 
                            [User].name AS name, 
                            [User].password AS password, 
                            [User].joinedDateTime AS joinedDate 
                        FROM [Project] 
                        INNER JOIN [ProjectMember] 
                            ON [Project].projectId = [ProjectMember].projectId 
                        INNER JOIN [User]
                            ON [Project].projectOwnerId = [User].userId
                        WHERE [ProjectMember].userId = @userid", conn);
                    sqlCmd.Parameters.AddWithValue("@userid", m_getProjectList.UserID);

                    using (SqlDataReader reader = sqlCmd.ExecuteReader())
                    {
                        if (reader.HasRows)
                        {
                            List<CCL.TableStructure.Project> projectList = new List<CCL.TableStructure.Project>();

                            while (reader.Read())
                            {
                                int projId = (int)reader["pid"];
                                string projName = (string)reader["pname"];
                                int head = (int)reader["head"];
                                int owner = (int)reader["poid"];

                                int userId = (int)reader["uid"];
                                string email = (string)reader["email"];
                                string name = (string)reader["name"];
                                string password = (string)reader["password"];
                                DateTime dateTime = (DateTime)reader["joinedDate"];

                                CCL.TableStructure.User user = new CCL.TableStructure.User(userId, name, email, password, dateTime);

                                CCL.TableStructure.Project proj = new CCL.TableStructure.Project(projId, projName, head, user);

                                projectList.Add(proj);
                            }

                            CCL.SocketMessage.Response.GetProjectList resp = new CCL.SocketMessage.Response.GetProjectList(projectList);
                            CCL.SocketMessage.Message respMsg = CCL.SocketMessage.Message.MessageResponseBuilder(resp);

                            returnBytes = respMsg.GetByte();
                        }
                        else
                        {
                            throw new Exception("등록되어 있는 프로젝트가 없습니다.");
                        }
                    }
                }
                catch (System.Exception ex)
                {
                    CCL.SocketMessage.Response.GetProjectList resp = new CCL.SocketMessage.Response.GetProjectList(ex.Message);
                    CCL.SocketMessage.Message respMsg = CCL.SocketMessage.Message.MessageResponseBuilder(resp);

                    returnBytes = respMsg.GetByte();
                }
                finally
                {
                    conn.Close();
                }
            }

            return returnBytes;
        }
    }
}
